module CPU(en,RA,Wr,Rd,M,rst,clk,datain,sel,seg,out,sin,sout,Rin);
input clk;   //时钟信号
//通用寄存器控制信号
input[1:0] RA;      
input Wr,Rd;
//PC寄存器控制信号   
input[1:0] M;            
input rst;    
//输入的4位数据
input[3:0] datain;
/*
en:控制输入数据的前高4位还是后低4位 
sin:控制输入的数据 
sout:控制输出的数据
*/
input en,sin,sout;  
input [7:0] Rin;//来自ALU的输入
output reg[7:0] out;     //输出到ALU的数据
output reg[2:0] sel;		  //数码管位选
output reg[7:0] seg;      //数码管段选

reg[7:0] R0,R1,R2,R3,PC; //4个通用寄存器，1个pc寄存器
reg[7:0] Q;	     //通用寄存器读出的数据
reg[7:0] D;      //输入的8位数据
reg[7:0] count; //分频计数用的
reg div_clk;     //分频后的时钟信号
reg[3:0] data; //LED灯显示用的


always @(posedge clk)
begin
	//分频
	if(count>=8'b11111111)
	begin
		count=0;
		div_clk=~div_clk;
	end
	else
		count=count+1;
		
	//读入数据
	if(sin)//从外部输入数据
		if(en)
			D[7:4]=datain;
		else
			D[3:0]=datain;
	else 	
		D=Rin;
end


always @(posedge clk)
begin
	//通用寄存器
	case({RA,Wr,Rd})
		4'b0001: R0=D;
		4'b0010: Q=R0;
		4'b0101: R1=D;
		4'b0110: Q=R1;
		4'b1001: R2=D;
		4'b1010: Q=R2;
		4'b1101: R3=D;
		4'b1110: Q=R3;
	endcase
end
always @(posedge div_clk)
begin 
//PC寄存器
		if(~rst)
			PC<=0;
		else 
		begin
		case(M)
			2'b11: PC<=D;//置数
			2'b01: PC<=PC+1; //自增
			2'b10: PC<=PC-1; //自减
		endcase
		end
end

//输出给ALU
always @(posedge clk)
begin 
	if(sout) 
		out<=Q;  //通用寄存器输出给ALU
	else 
		out<=PC; //PC寄存器输出给ALU
end

//数码管输出
always @(posedge clk)
begin
	if(sel>=3'd8)
		sel<=0;
	sel<=sel+1;
	case(sel)
		0: data<=D[7:4]; 
		1: data<=D[3:0]; 
		2: data<=0;
		3: data<=0;
		4: data<=PC[7:4]; //pc寄存器
		5: data<=PC[3:0]; //pc寄存器
		6: data<=Q[7:4];//通用寄存器
		7: data<=Q[3:0];//通用寄存器
	endcase
	case(data)
			4'h0: seg<=8'h3F;
			4'h1: seg<=8'h06;
			4'h2: seg<=8'h5B;
			4'h3: seg<=8'h4F;
			4'h4: seg<=8'h66;
			4'h5: seg<=8'h6D;
			4'h6: seg<=8'h7D;
			4'h7: seg<=8'h07;
			4'h8: seg<=8'h7F;
			4'h9: seg<=8'h6F;
			4'hA: seg<=8'h77;
			4'hB: seg<=8'h7C;
			4'hC: seg<=8'h39;
			4'hD: seg<=8'h5E;
			4'hE: seg<=8'h79;
			4'hF: seg<=8'h71;
			default: seg<=8'h00;
		endcase
end
endmodule 